package com.sm.healthy.ui.fragment.historyfrag

import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.navigation.navOptions
import com.sm.healthy.utils.CacheUtil
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.formatter.DefaultAxisValueFormatter
import com.github.mikephil.charting.formatter.ValueFormatter
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet
import com.sm.healthy.R
import com.sm.healthy.adapter.HistoryTemperatureAdapter
import com.sm.healthy.base.BaseFragment
import com.sm.healthy.data.bean.TemperatureEntity
import com.sm.healthy.databinding.FragmentHistoryTemperatureBinding
import com.sm.healthy.ext.clearData
import com.sm.healthy.ext.getTimeFormat
import com.sm.healthy.model.HistoryTemperatureModel
import com.sm.healthy.utils.CalendarUtil
import io.freespiritsocial.user.ext.init
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import java.math.RoundingMode
import kotlin.math.max
import kotlin.math.min

class HistoryTemperatureFlag :
    BaseFragment<HistoryTemperatureModel, FragmentHistoryTemperatureBinding>() {

    private var curWeek = CalendarUtil.curWeek()
        set(value) {
            field = value
            lazyLoadData()
        }
    private var curMonth = CalendarUtil.curMonth()
        set(value) {
            field = value
            lazyLoadData()
        }
    private var isWeek = true

    private val adapter by lazy(LazyThreadSafetyMode.NONE) {
        HistoryTemperatureAdapter().apply {
            addHeaderView(layoutInflater.inflate(R.layout.header_history_temperature, null))
        }
    }

    override fun layoutId(): Int {
        return R.layout.fragment_history_temperature
    }

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.rlData.init(adapter)
        mDatabind.click = Click()
        mDatabind.rbWeek.isChecked = true

        mDatabind.tabLine.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                R.id.rb_data -> {
                    mDatabind.rlData.visibility = View.VISIBLE
                    mDatabind.llChat.visibility = View.GONE
                }

                R.id.rb_line -> {
                    mDatabind.llChat.visibility = View.VISIBLE
                    mDatabind.rlData.visibility = View.GONE
                }
            }
        }

        mDatabind.rbGroup.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                R.id.rb_week -> {
                    isWeek = true
                    curWeek = curWeek
                }
                R.id.rb_month -> {
                    isWeek = false
                    curMonth = curMonth
                }
            }
        }

    }

    override fun lazyLoadData() {
        val before: Long
        val after: Long
        if (isWeek) {
            before = CalendarUtil.weekStart(curWeek)
            after = CalendarUtil.weekEnd(curWeek)
            mDatabind.tvSelectedTime.text =
                "${before.getTimeFormat("MM-dd")}~${after.getTimeFormat("MM-dd")}"
        } else {
            before = CalendarUtil.monthStart(curMonth)
            after = CalendarUtil.monthEnd(curMonth)
            mDatabind.tvSelectedTime.text = "${before.getTimeFormat("yyyy年MM月")}"
        }

        mViewModel.getTemperatureByTime(before, after).observe(this) {
            adapter.clearData()
            adapter.addData(it)
            val entries: MutableList<Entry> = ArrayList()

            for (oxygenValue in it) {
                val bloodPressureEntity = TemperatureEntity(
                    CacheUtil.getCurUid(),
                    oxygenValue.id,
                    oxygenValue.temperature,
                    oxygenValue.levelTemperature,
                    oxygenValue.timeLong
                )
                entries.add(
                    Entry(
                        bloodPressureEntity.timeLong.toFloat(),
                        bloodPressureEntity.temperature,
                        bloodPressureEntity
                    )
                )
            }
            setChartData(before, after, entries)
        }
    }

    private fun setChartData(
        before: Long,
        after: Long, entries1: List<Entry>
    ) {
        mDatabind.llChat.setTouchEnabled(false)

        val dataSet1 = LineDataSet(entries1, "舒张压")

        dataSet1.apply {
            lineWidth = 0.8f
            circleRadius = 2.0f
            circleHoleRadius = 1.0f
            setCircleColor(Color.parseColor("#65B3FF"))
            color = Color.parseColor("#65B3FF")
            valueFormatter = object : ValueFormatter() {

                override fun getFormattedValue(value: Float): String {
                    return value.toString()
                }
            }
        }

        val sets = ArrayList<ILineDataSet>()
        sets.add(dataSet1)

        val xAxis = mDatabind.llChat.xAxis

        xAxis.apply {
            position = XAxis.XAxisPosition.BOTTOM
            setDrawGridLines(false)// 是否绘制网格线，默认true
            setDrawAxisLine(true)// 是否绘制坐标轴,默认true
            setDrawLabels(true)// 是否绘制标签,默认true
            granularity = 1f//间隔
            setLabelCount(7, true)
            axisMinimum = before.toFloat()
            axisMaximum = after.toFloat()

            valueFormatter = object : DefaultAxisValueFormatter(0) {

                override fun getFormattedValue(value: Float): String {
                    return value.toBigDecimal().setScale(0, RoundingMode.HALF_UP).toLong()
                        .getTimeFormat("MM-dd")
                }

                override fun getDecimalDigits(): Int {
                    return 0
                }
            }
        }

        val axisLeft = mDatabind.llChat.axisLeft
        axisLeft.apply {
            textColor = Color.parseColor("#65B3FF")
            setLabelCount(6, true)
            axisMinimum = 32f
            axisMaximum = 42f
            valueFormatter = object : DefaultAxisValueFormatter(0) {
                override fun getFormattedValue(value: Float): String {
                    return value.toInt().toString()
                }

                override fun getDecimalDigits(): Int {
                    return 0
                }
            }
        }

        val axisRight = mDatabind.llChat.axisRight
        axisRight.apply {
            isEnabled = false// 不绘制右侧的轴线
        }

        val lineData = LineData(sets)

        mDatabind.llChat.apply {
            setBackgroundColor(Color.WHITE)
            description.text = ""// 右下角的描述文本
            setDrawGridBackground(false)
            setNoDataText("")// 没有数据时样式
            setDrawBorders(false) // 绘制区域边框绘制，默认false
            setMaxVisibleValueCount(999)// 数据点上显示的标签，最大数量，默认100。且dataSet.setDrawValues(true);必须为true。只有当数据数量小于该值才会绘制标签

            legend.apply {// 获取图例，但是在数据设置给chart之前是不可获取的
                isEnabled = false// 是否绘制图例
            }

            data = lineData
            invalidate()
        }
    }

    inner class Click {
        fun dayAfter() {
            if (isWeek) curWeek++ else curMonth++
        }

        fun dayBefore() {
            if (isWeek) curWeek-- else curMonth--
        }

        fun goMeasure() {
            nav().navigateAction(R.id.temperatureMFragment,
                navOptions = navOptions {
                    popUpTo(R.id.temperatureMFragment) { inclusive = true }
                    anim {
                        exit = me.hgj.jetpackmvvm.R.anim.exit
                        enter = me.hgj.jetpackmvvm.R.anim.enter
                        popEnter = me.hgj.jetpackmvvm.R.anim.popenter
                        popExit = me.hgj.jetpackmvvm.R.anim.popexit
                    }
                })
        }
    }
}